package cn.wen.yinxiu.works.service.impl;

import cn.wen.yinxiu.common.enums.DelEnum;
import cn.wen.yinxiu.common.enums.StatusEnum;
import cn.wen.yinxiu.common.toolkit.DateUtils;
import cn.wen.yinxiu.works.dao.DiagnosisDao;
import cn.wen.yinxiu.works.entity.DiagnosisEntity;
import cn.wen.yinxiu.works.entity.WorksDataEntity;
import cn.wen.yinxiu.works.feign.UserFeignService;
import cn.wen.yinxiu.works.service.DiagnosisService;
import cn.wen.yinxiu.works.service.WorksDataService;
import cn.wen.yinxiu.works.service.WorksService;
import cn.wen.yinxiu.works.to.UserDataInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service("diagnosisService")
public class  DiagnosisServiceImpl extends ServiceImpl<DiagnosisDao, DiagnosisEntity> implements DiagnosisService {

    @Autowired
    private DiagnosisDao diagnosisDao;

    @Autowired
    private UserFeignService userFeignService;

    @Autowired
    private WorksDataService worksDataService;

    @Override
    public DiagnosisEntity getWorksDiagnosis(Long userId) {
        // 1.获取当天的时间
        String currentDayStartTime = DateUtils.getToDayStartTime();
        QueryWrapper<DiagnosisEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("create_time", currentDayStartTime);
        queryWrapper.eq("user_id", userId);
        return diagnosisDao.selectOne(queryWrapper);
    }

    @Override
    public boolean doDiagnosisDataStatisticsTimer() {
        // 1.获取当前WorksData中的数据
        // 1.1.获取当天的时间开始就是统计最近七天的数据
        String currentDayStartTime = DateUtils.getToDayStartTime();
        // 获取当前用户量
        int size = userFeignService.getUserIdList().getData().size();
        // 1.2.获取当前的所有数据（就已经包括所有用户）
        List<WorksDataEntity> currentDataList = worksDataService.getWorksDataByTime(currentDayStartTime);
        // 2.获取WorksData七天内最近一天的数据
        String preDayTime = DateUtils.decDaysOfDay(7, currentDayStartTime);
        List<WorksDataEntity> preDataList = worksDataService.getWorksDataByNumTime(preDayTime);
        // 3.计算对应的数据（计算7天内增加的数据 包括：用户/全体作品量、粉丝量、点赞量、收藏量、播放量、同时计算超过率）
        // 需要先判断是否为
        if (currentDataList == null) {
            // 说明了还未拥有数据 直接返回异常
            return false;
        } 
        // 使用Map来存储preDataList 方便取
        Map<Long, WorksDataEntity> map = new HashMap<>();
        preDataList.stream().forEach(item-> {
            map.put(item.getUserId(), item);
        });
        // 循环添加数据
        List<DiagnosisEntity> diagnosisList = new ArrayList<>();
        for (WorksDataEntity currentWorksData : currentDataList) {
            // 判断当前数据是否为空
            if (currentWorksData == null) {
                // 说明了还未拥有数据 直接返回异常 跳过
                continue;
            }
            // 如果当前存在数据  preData不存在则说明数据是此时这今天添加的还未结算
            WorksDataEntity preWorksData = map.get(currentWorksData.getUserId());
            if (currentWorksData != null && preWorksData == null) {
                preWorksData = new WorksDataEntity();
                preWorksData.setFansNum(0L);
                preWorksData.setOtherWorksNum(0L);
                preWorksData.setOtherPlayNum(0L);
                preWorksData.setOtherLikeNum(0L);
                preWorksData.setOtherCollectNum(0L);
                preWorksData.setOtherFansNum(0L);
                preWorksData.setPlayNum(0L);
                preWorksData.setWorksCollectNum(0L);
                preWorksData.setWorksLikeNum(0L);
                preWorksData.setWorksNum(0L);
                preWorksData.setPlayNum(0L);
            }
            DiagnosisEntity target = new DiagnosisEntity();
            Long worksNum = currentWorksData.getWorksNum() - preWorksData.getWorksNum();
            Long playNum = currentWorksData.getPlayNum() - preWorksData.getPlayNum();
            Long likeNum = currentWorksData.getWorksLikeNum() - preWorksData.getWorksLikeNum();
            Long collectNum = currentWorksData.getWorksCollectNum() - preWorksData.getWorksCollectNum();
            Long fansNum = currentWorksData.getFansNum() - preWorksData.getFansNum();
            Long totalWorksNum = currentWorksData.getOtherWorksNum() - preWorksData.getOtherWorksNum();
            Long totalLikeNum = currentWorksData.getOtherLikeNum() - preWorksData.getOtherLikeNum();
            Long totalCollectNum = currentWorksData.getOtherCollectNum() - preWorksData.getOtherCollectNum();
            Long totalFansNum = currentWorksData.getOtherFansNum() - preWorksData.getOtherFansNum();
            Long totalPlayNum = currentWorksData.getOtherPlayNum() - preWorksData.getOtherPlayNum();
            target.setPlayNum(playNum);
            target.setWorksNum(worksNum);
            target.setLikeNum(likeNum);
            target.setCollectNum(collectNum);
            target.setFansNum(fansNum);
            target.setOtherWorksNum(totalWorksNum);
            target.setOtherCollectNum(totalCollectNum);
            target.setOtherFansNum(totalFansNum);
            target.setOtherLikeNum(totalLikeNum);
            target.setOtherPlayNum(totalPlayNum);

            target.setCreateTime(DateUtils.getDateFromStr(currentDayStartTime));
            target.setUserId(currentWorksData.getUserId());
            diagnosisList.add(target);
        }
        // 设置对应的超过率
        getWorksExceed(diagnosisList, size - 1);
        // 批量插入
        boolean res = this.saveBatch(diagnosisList);
        return res;
    }

    @Override
    public DiagnosisEntity getWorksDiagnosisByTime(String currentWeekStartTime, Long userId) {
        QueryWrapper<DiagnosisEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("create_time", currentWeekStartTime);
        return diagnosisDao.selectOne(queryWrapper);
    }

    private void getWorksExceed(List<DiagnosisEntity> diagnosisList, int userSize) {
        int size = diagnosisList.size() - 1;
        // 1.1.对播放量进行排序
        Collections.sort(diagnosisList, new Comparator<DiagnosisEntity>() {
            @Override
            public int compare(DiagnosisEntity o1, DiagnosisEntity o2) {
                if(o1.getPlayNum() > o2.getPlayNum())
                    return 1;
                else if(o1.getPlayNum() < o2.getPlayNum())
                    return -1;
                else
                    return 0;
                /*这样是属于升序排列，如果要逆序，就互换return 1 和return -1的位置*/
            }
        });
        for (int i = 0; i <= size; i++) {
            diagnosisList.get(i).setPlayExceed(Double.parseDouble(String.format("%.4f", ((Double.valueOf(i) / Double.valueOf(userSize)) * 100))));
        }
        // 1.2.对粉丝进行排序
        Collections.sort(diagnosisList, new Comparator<DiagnosisEntity>() {
            @Override
            public int compare(DiagnosisEntity o1, DiagnosisEntity o2) {
                if(o1.getFansNum() > o2.getFansNum())
                    return 1;
                else if(o1.getFansNum() < o2.getFansNum())
                    return -1;
                else
                    return 0;
                /*这样是属于升序排列，如果要逆序，就互换return 1 和return -1的位置*/
            }
        });
        for (int i = 0; i <= size; i++) {
            diagnosisList.get(i).setFansExceed(Double.parseDouble(String.format("%.4f", ((Double.valueOf(i) / Double.valueOf(userSize)) * 100))));
        }

        // 1.3.对收藏量进行排序
        Collections.sort(diagnosisList, new Comparator<DiagnosisEntity>() {
            @Override
            public int compare(DiagnosisEntity o1, DiagnosisEntity o2) {
                if(o1.getCollectNum() > o2.getCollectNum())
                    return 1;
                else if(o1.getCollectNum() < o2.getCollectNum())
                    return -1;
                else
                    return 0;
                /*这样是属于升序排列，如果要逆序，就互换return 1 和return -1的位置*/
            }
        });
        for (int i = 0; i <= size; i++) {
            diagnosisList.get(i).setCollectExceed(Double.parseDouble(String.format("%.4f", ((Double.valueOf(i) / Double.valueOf(userSize)) * 100))));
        }

        // 1.4.对作品量进行排序
        Collections.sort(diagnosisList, new Comparator<DiagnosisEntity>() {
            @Override
            public int compare(DiagnosisEntity o1, DiagnosisEntity o2) {
                if(o1.getWorksNum() > o2.getWorksNum())
                    return 1;
                else if(o1.getWorksNum() < o2.getWorksNum())
                    return -1;
                else
                    return 0;
                /*这样是属于升序排列，如果要逆序，就互换return 1 和return -1的位置*/
            }
        });
        for (int i = 0; i <= size; i++) {
            diagnosisList.get(i).setWorksExceed(Double.parseDouble(String.format("%.4f", ((Double.valueOf(i) / Double.valueOf(userSize)) * 100))));
        }

        // 1.5对点赞量进行排序
        Collections.sort(diagnosisList, new Comparator<DiagnosisEntity>() {
            @Override
            public int compare(DiagnosisEntity o1, DiagnosisEntity o2) {
                if(o1.getLikeNum() > o2.getLikeNum())
                    return 1;
                else if(o1.getLikeNum() < o2.getLikeNum())
                    return -1;
                else
                    return 0;
                /*这样是属于升序排列，如果要逆序，就互换return 1 和return -1的位置*/
            }
        });
        for (int i = 0; i <= size; i++) {
            diagnosisList.get(i).setLikeExceed(Double.parseDouble(String.format("%.4f", ((Double.valueOf(i) / Double.valueOf(userSize)) * 100))));
        }
    }

}